import React, { Component } from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import { Badge, Button, message, Modal, Popover } from 'antd';
import menuRoute from 'routes/menuRoute';
import errorMessage from 'share/errorMessage';
import ResizeTable from 'components/resize-table';
import reimburseService from '../reimbursement/reimbursement.service';
import 'styles/expense-reimbursement-control/reimbursement/reimbursement.scss'

class ReimbursementSubmission extends Component {

  constructor(props) {
    super(props);
    this.state = {
      columns: [
        {
          title: messages('common.sequence'/*序号*/),
          dataIndex: 'index',
          width: 48,
          render: (value, record, index) => this.renderColumns({ value, record, index, dataIndex: 'index' })
        },
        {
          title: messages('expense-reimbursement-control.key18')/*规则编码*/,
          dataIndex: 'code',
          width: 120
        },
        {
          title: messages('expense-reimbursement-control.key31')/*规则名称*/,
          dataIndex: 'name',
          render: value => <Popover placement="topLeft" content={value}>{value}</Popover>
        },
        {
          title: messages('expense-reimbursement-control.key32')/*分配公司*/,
          dataIndex: 'companys',
          render: value => this.renderColumns({ value, dataIndex: 'companys' })
        },
        {
          title: messages('expense-reimbursement-control.key53')/*适用单据*/,
          dataIndex: 'forms',
          render: value => this.renderColumns({ value, dataIndex: 'forms' })
        },
        {
          title: messages('expense-reimbursement-control.key62')/*控制力度*/,
          dataIndex: 'controlLevel',
          render: value => this.renderColumns({ value, dataIndex: 'controlLevel' })
        },
        {
          title: messages('expense-reimbursement-control.key64')/*提示内容*/,
          dataIndex: 'message',
          render: value => this.renderColumns({ value, dataIndex: 'message' })
        },
        {
          title: messages('common.column.status'/*状态*/),
          dataIndex: 'status',
          width: 80,
          render: value => this.renderColumns({ value, dataIndex: 'status' })
        },
        {
          title: messages('common.operation'/*操作*/),
          dataIndex: 'ruleOID',
          width: 120,
          render: (value, record) => this.renderColumns({ value, record, dataIndex: 'ruleOID' })
        }
      ],
      data: [],
      page: 0,
      pageSize: 10,
      pagination: { total: 0 },
      setOfBooksId: props.nowSetOfBooks.id,
    };
  }

  componentDidMount() {
    this.getList();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.nowSetOfBooks.id !== this.props.nowSetOfBooks.id) {
      this.setState({ setOfBooksId: nextProps.nowSetOfBooks.id }, () => {
        this.getList();
      });
    }
  }

  getList = () => {
    const { tenantMode } = this.props;
    const { page, pageSize, setOfBooksId } = this.state;
    let params = { page, size: pageSize, businessType: 1002 };
    tenantMode && (params.setOfBooksId = setOfBooksId);
    this.setState({ loading: true });
    reimburseService.getRuleList(params)
      .then(res => {
        this.setState({
          data: res.data,
          loading: false,
          pagination: {
            total: Number(res.headers['x-total-count'] || 0),
            onChange: this.onChangePager,
            current: page + 1
          }
        });
      })
      .catch(e => {
        errorMessage(e.response);
        this.setState({ loading: false });
      });
  };

  //分页
  onChangePager = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getList();
      });
    }
  };

  //删除规则
  deleteRule = (e, ruleOID) => {
    e.stopPropagation();
    Modal.confirm({
      title: messages('expense-reimbursement-control.key41')/*确认删除？*/,
      content: messages('expense-reimbursement-control.key42')/*分配的公司将不可用该规则，你还要继续吗？*/,
      onOk: () => {
        this.setState({ loading: true });
        reimburseService.deleteRule(ruleOID)
          .then(() => {
            this.getList();
            message.success(messages('common.delete.success', { name: '' })/*删除成功*/);
          })
          .catch(e => {
            errorMessage(e.response);
            this.setState({ loading: false });
          });
      },
    });
  };


  handleRowClick = (record) => {
    this.context.router.replace(
      menuRoute.getRouteItem('reimbursement-submission-detail')
        .url
        .replace(/(.*):setOfBooksId(.*):ruleOID(.*)/, `$1${this.props.nowSetOfBooks.id}$2${record.ruleOID}`)
    );
  };

  //新建规则
  newRule = () => {
    this.context.router.push(
      menuRoute.getRouteItem('reimbursement-submission-new').url.replace(':setOfBooksId', this.props.nowSetOfBooks.id)
    );
  };

  renderColumns = (params) => {
    const { dataIndex, value, record, index } = params;
    if (dataIndex === 'index') {
      return index + 1 + this.state.pageSize * this.state.page;
    }

    if (dataIndex === 'status') {
      return (
        <Badge
          status={value ? 'success' : 'error'}
          text={value ? messages('common.status.enable') : messages('common.status.disable')}/>);
    }

    if (dataIndex === 'ruleOID') {
      return record.source === 1001 && !this.props.tenantMode
        ? '-'
        : (<div className="operate-column">
            <a className="delete" onClick={e => this.deleteRule(e, value)}>{messages('common.delete')/*删除*/}</a>
          </div>
        );
    }

    if (dataIndex === 'forms') {
      return value &&  value.length
        ? <Popover
          placement="topLeft"
          overlayStyle={{ maxWidth: 500 }}
          content={value.map(item => item.formName).join('、')}>
          {value.map(item => item.formName).join('、')}
        </Popover>
        : messages('expense-reimbursement-control.key28');/*通用*/
    }

    if (dataIndex === 'controlLevel') {
      return value === 'WARN'
        ? messages('expense-reimbursement-control.key46')/*警告*/
        : messages('expense-reimbursement-control.key47');/*禁止*/
    }

    if (dataIndex === 'message') {
      return (
        <Popover
          placement="topLeft"
          overlayStyle={{ maxWidth: 500 }}
          content={value}>
          {value}
        </Popover>);
    }

    if (dataIndex === 'companys') {
      return value &&  value.length
        ? <Popover
          placement="topLeft"
          overlayStyle={{ maxWidth: 500 }}
          content={value.map(item => item.name).join('、')}>
          {value.map(item => item.name).join('、')}
        </Popover>
        : messages('expense-reimbursement-control.key28');/*通用*/
    }
  };

  render() {
    const { loading, columns, data, pagination } = this.state;
    return (
      <section className="reimbursement">
        <Button
          type="primary"
          icon="plus"
          className="new-rule-btn"
          onClick={this.newRule}>
          {messages('expense-reimbursement-control.key43')/*新建规则*/}
        </Button>
        <ResizeTable
          rowKey="ruleOID"
          loading={loading}
          columns={columns}
          dataSource={data}
          pagination={pagination}
          onRow={record => ({
            onClick: () => this.handleRowClick(record)
          })}
          bordered
          size="middle"
        />
      </section>
    );
  }
}

ReimbursementSubmission.propTypes = {
  nowSetOfBooks: React.PropTypes.object
};

ReimbursementSubmission.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    company: state.login.company,
    tenantMode: state.main.tenantMode
  };
}

export default connect(mapStateToProps)(ReimbursementSubmission);

